package com.app.controller.backstage;


import com.alibaba.fastjson.JSONObject;
import com.app.common.EducationTool;
import com.app.common.ExperienceTool;
import com.app.common.NatureTool;
import com.app.common.ScaleTool;
import com.app.controller.TemplateMessageController;
import com.app.model.*;
import com.app.service.*;
import com.app.util.Result;
import com.app.util.SMSUtils;
import com.app.util.TokenUtils;
import com.app.vo.JobFairCompanyPostVo;
import com.app.vo.JobFairCompanyVo;
import com.app.vo.ScaleVo;
import com.google.common.collect.Maps;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.TemplateExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

@RestController
@Controller
public class CompanyController {

    @Autowired
    AdminUserService adminUserService;
    @Autowired
    JobFairCompanyService jobFairCompanyService;
    @Autowired
    JobPublishService jobPublishService;
    @Autowired
    ComRecruitersService comRecruitersService;
    @Autowired
    EnterpriseService enterpriseService;
    @Autowired
    UserService userService;
    @Autowired
    PositionService positionService;
    @Autowired
    JobFairCompanyPostService jobFairCompanyPostService;

    @Autowired
    IndustryService industryService;
    @Autowired
    EnterpriseAlbumService enterpriseAlbumService;
    @Autowired
    TemplateMessageController templateMessageController;
    @Autowired
    CustomerService customerService;

    @GetMapping("/getJobFairList")
    public Result<Object> getJobFairList(
            int page, int limit,
            @RequestParam(required = false) String keyWord,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer sid,
            @RequestParam(required = false) Integer auditState,
            HttpServletRequest request) throws ParseException {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobFairCompanyModel model = new JobFairCompanyModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        model.setKeyWord(keyWord);
        model.setSid(sid);
        model.setAuditState(auditState);
        return Result.success(jobFairCompanyService.jobFairList(model));

    }


    /**
     * 修改参会企业状态
     *
     * @param id
     * @param auditState
     * @param request
     * @return
     */
    @PostMapping("/updateJobFair")
    public Result<Object> updateJobFair(
            Integer id,
            Integer auditState,
            @RequestParam(required = false) String refuseCause,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        JobFairCompanyModel model = jobFairCompanyService.getModelById(id);
        model.setAuditState(auditState);
        model.setRefuseCause(refuseCause);
        jobFairCompanyService.update(model);
        return Result.success("操作成功");

    }

    @GetMapping("bakGetEntFairList")//后台查参加招聘会公司列表
    public Result<Object> getNewsList(HttpServletRequest request,
                                      @RequestParam(required = false) String keyWord,
                                      @RequestParam(required = false) String startTime,
                                      @RequestParam(required = false) String endTime,
                                      int page,
                                      int limit) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobFairCompanyModel model = new JobFairCompanyModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setKeyWord(keyWord);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        List<JobFairCompanyModel> companyList = jobFairCompanyService.getLIstByModel(model);//查参会企业表的会议id和企业id
        int count = jobFairCompanyService.getCountByModel(model);//查数量
        JobFairCompanyVo vo = new JobFairCompanyVo();
        vo.setCount(count);
        vo.setList(companyList);
        return Result.success(vo);
    }

    @GetMapping("/getPublishListByModel")
    public Result<Object> getPublishListByModel(
            int page, int limit,
            @RequestParam(required = false) String keyWord,
            @RequestParam(required = false) Integer state,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer orderDate,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobPublishModel model = new JobPublishModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setKeyword(keyWord);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        model.setOrderDate(orderDate);
        model.setRecruitState(state);
        return Result.success(jobPublishService.publishListByModel(model));
    }

    @RequestMapping(value = "findPublishListById", method = RequestMethod.GET)
    public Result<Object> findPublishListById(int id, HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }

        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        return Result.success(jobPublishService.publishListById(id));
    }

    @GetMapping("/toExaminePublish")
    public Result<Object> toExaminePublish(
            @RequestParam(required = false) int id,
            @RequestParam(required = false) int stateType,
            @RequestParam(required = false) String remarks,
            HttpServletRequest request) throws IOException {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobPublishModel model = jobPublishService.findAllJobById(id);
        model.setRecruitState(stateType);
        model.setRemarks(remarks);
        jobPublishService.update(model);
        UserModel userModel = userService.getUserByRId(model.getRecId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Timestamp timestamp = Timestamp.valueOf(LocalDateTime.now());
        String time = sdf.format(timestamp);
        if (stateType == 1) {
            if (stateType == 1) {
                SMSUtils.examine(userModel.getMobile());//短信通知HR
            }
            if (stateType == 3) {
                //审核通过
                JSONObject data = new JSONObject();
                //岗位名称
                JSONObject thing1 = new JSONObject();
                thing1.put("value", model.getJobTitle());
                data.put("thing1", thing1);
                //审核状态
                JSONObject phrase2 = new JSONObject();
                phrase2.put("value", "审核通过");
                data.put("phrase2", phrase2);
                //审核时间
                JSONObject time3 = new JSONObject();
                time3.put("value", time);
                data.put("time3", time3);
                //金额
                JSONObject thing4 = new JSONObject();
                thing4.put("value", "岗位信息审核通过，岗位已上架");
                data.put("thing4", thing4);
                Result<SendModel> sendModelResult = templateMessageController.JobReview(data, userModel.getOpenid());
                System.out.println(sendModelResult);
            }
            if (stateType == 2) {
                //审核失败
                JSONObject data = new JSONObject();
                //岗位名称
                JSONObject thing1 = new JSONObject();
                thing1.put("value", model.getJobTitle());
                data.put("thing1", thing1);
                //审核状态
                JSONObject phrase2 = new JSONObject();
                phrase2.put("value", "审核失败");
                data.put("phrase2", phrase2);
                //审核时间
                JSONObject time3 = new JSONObject();
                time3.put("value", time);
                data.put("time3", time3);
                //金额
                JSONObject thing4 = new JSONObject();
                thing4.put("value", "岗位信息审核失败，请重新发布");
                data.put("thing4", thing4);
                Result<SendModel> sendModelResult = templateMessageController.JobReview(data, userModel.getOpenid());
                System.out.println(sendModelResult);
            }
        }
        return Result.success("操作成功");
    }

    @GetMapping("/getCompanyList")
    public Result<Object> getCompanyList(
            int page, int limit,
            @RequestParam(required = false) String keyWord,
            @RequestParam(required = false) Integer scaleId,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }

        EnterpriseModel model = new EnterpriseModel();
        model.setPage(page);
        model.setLimit(limit);
        model.setKeyWord(keyWord);
        model.setScaleId(scaleId);
        return Result.success(enterpriseService.getCompanyList(model));

    }

    @GetMapping("/getJobPublishList")
    public Result<Object> getJobPublishList(
            int page, int limit,
            @RequestParam(required = false) String keyWord,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime,
            @RequestParam(required = false) Integer enrollId,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobPublishModel model = new JobPublishModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setJobTitle(keyWord);
        model.setStartTime(startTime);
        model.setEndTime(endTime);
        model.setEnrollId(enrollId);
        return Result.success(jobPublishService.getJobPublishList(model));

    }

    @GetMapping("/getJobFairPublishList")
    public Result<Object> getJobFairPublishList(
            int page, int limit,
            @RequestParam(required = false) Integer sid,
            @RequestParam(required = false) Integer cid,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        JobFairCompanyPostModel model = new JobFairCompanyPostModel();
        model.setPage((page - 1) * limit);
        model.setLimit(limit);
        model.setCid(cid);
        model.setSid(sid);
        JobFairCompanyPostVo vo = new JobFairCompanyPostVo();
        List<JobFairCompanyPostModel> modelList = jobFairCompanyPostService.getLIstByModel(model);
        for (int i = 0; i < modelList.size(); i++) {
            int jobType = modelList.get(i).getJobType();
            PositionModel positionModel = positionService.getModelById(jobType);
            modelList.get(i).setJobTypeText(positionModel.getJobTitle());
            for (int j = 0; j < ExperienceTool.EXPERIENCE_VO_LIST.size(); j++) {//
                if (modelList.get(i).getExpId() == ExperienceTool.EXPERIENCE_VO_LIST.get(j).getId()) {
                    modelList.get(i).setExpIdText(ExperienceTool.EXPERIENCE_VO_LIST.get(j).getData());
                }
            }
            for (int j = 0; j < EducationTool.EDUCATION_VO_LIST.size(); j++) {
                if (modelList.get(i).getEduId() == EducationTool.EDUCATION_VO_LIST.get(j).getId()) {
                    modelList.get(i).setEduIdText(EducationTool.EDUCATION_VO_LIST.get(j).getData());
                }

            }

        }
        int count = jobFairCompanyPostService.getCountByModel(model);
        vo.setCount(count);
        vo.setList(modelList);

        return Result.success(vo);

    }

    /**
     * 查询企业详情
     *
     * @param id
     * @return
     */
    @GetMapping("/getComDetails")
    public Result<Object> getComDetails(
            Integer id,
            HttpServletRequest request) {
        String token = request.getHeader("token");
        String userId = TokenUtils.nothingness(token);
        if (userId == null) {
            return Result.error(405, "token不存在");
        }
        AdminUserModel user = adminUserService.getUserById(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(405, "用户不存在");
        }
        EnterpriseModel model = enterpriseService.findModelById(id);
        model.setNatureText(NatureTool.myMap.get(model.getNature()));
        for (ScaleVo vo : ScaleTool.SCALE_VO_LIST) {
            if (model.getScaleId() != null) {
                if (model.getScaleId() == vo.getId()) {
                    model.setScaleName(vo.getData());
                }
            }

        }
        IndustryModel industryModel = industryService.getModelByCode(model.getEnterpriseType());
        model.setEnterpriseTypeText(industryModel.getIndustryName());
        List<EnterpriseAlbumModel> enterpriseAlbumModelList = enterpriseAlbumService.getListByComId(model.getId());
        model.setAlbumModelList(enterpriseAlbumModelList);
        return Result.success(model);

    }


    /**
     * 查询格街道注册用户数量
     *
     * @return
     */
    @GetMapping("/getCustomerByStreet")
    public Result<Object> getCustomerByStreet(@RequestParam(required = false) String startTime,
                                              @RequestParam(required = false) String endTime) {
        return Result.success(customerService.getCustomerByStreet(startTime,endTime));

    }
    /**
     * 查询格街道注册企业数量
     *
     * @return
     */
    @GetMapping("/getComByStreet")
    public Result<Object> getComByStreet(@RequestParam(required = false) String startTime,
                                         @RequestParam(required = false) String endTime) {
        return Result.success(enterpriseService.getComByStreet(startTime,endTime));

    }

    /**
     * 查询格街道注册用户花名册
     *
     * @return
     */
    @GetMapping("/getCustomerByStreetId")
    public Result<Object> getCustomerByStreet(CustomerModel model) {
        return Result.success(customerService.getCustomerPageByStreetId(model));

    }
    /**
     * 查询格街道注册企业花名册
     *
     * @return
     */
    @GetMapping("/getComByStreetId")
    public Result<Object> getComByStreetId(EnterpriseModel model) {
        return Result.success(enterpriseService.getComPageByStreetId(model));

    }
    /**
     * 导出花名册
     *
     * @return
     */
    @PostMapping({"/exportRoster"})
    @ResponseBody
    public void exportRoster(HttpServletResponse response, @RequestParam(required = false) String startTime,
                             @RequestParam(required = false) String endTime) {

        List<CustomerModel> list = customerService.getCustomerAndStreet(startTime,endTime);
        Map map = Maps.newHashMap();
        map.put("list", list);
        ClassPathResource classPathResource = new ClassPathResource("C:/upload/roster_tables.xlsx");
        String path = classPathResource.getPath();
        TemplateExportParams templateExportParams1 = new TemplateExportParams(path);
        Workbook wb = ExcelExportUtil.exportExcel(templateExportParams1, map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 导出花名册
     *
     * @return
     */
    @PostMapping({"/exportComRoster"})
    @ResponseBody
    public void exportComRoster(HttpServletResponse response, @RequestParam(required = false) String startTime,
                                @RequestParam(required = false) String endTime) {

        List<EnterpriseModel> list = enterpriseService.getComAndStreet(startTime,endTime);
        Map map = Maps.newHashMap();
        map.put("list", list);
        ClassPathResource classPathResource = new ClassPathResource("C:/upload/com_roster_tables.xlsx");
        String path = classPathResource.getPath();
        TemplateExportParams templateExportParams1 = new TemplateExportParams(path);
        Workbook wb = ExcelExportUtil.exportExcel(templateExportParams1, map);
        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
        String fileName = "企业花名册" + time + ".xlsx";
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            wb.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
